import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:pax_info_app/ui/widgets/Animation/FadeAnimation.dart';
import 'package:pax_info_app/model/sys_info.dart';
import 'package:pax_info_app/repository/app_repository.dart';
import 'package:date_format/date_format.dart';
import 'package:pax_info_app/ui/pages/tab_control.dart';
import 'package:pax_info_app/utils/uidata.dart';

class LoginPage extends StatefulWidget {
  LoginPage();

  @override
  State createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  bool _showPwd = false;
  late bool _isRemember;
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  @override
  void initState() {
    _initData();
    super.initState();
  }

  void _initData() async {
    _isRemember = false;
    await SysInfo.instance.load();
    _isRemember = SysInfo.instance.isRemember??false;
    if (_isRemember) {
      String username = SysInfo.instance.userName??'';
      String password = SysInfo.instance.password??'';

      _usernameController.text = username;
      _passwordController.text = password;
    } else {
      _usernameController.text = '';
      _passwordController.text = '';
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    // SysInfo.instance.statusHeight = MediaQuery.of(context).padding.top;
    SysInfo.instance.deviceSize = MediaQuery.of(context).size;

    return Scaffold(
        backgroundColor: Colors.white,
        body: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Container(
                height: 400,
                decoration: const BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage('assets/images/background.png'),
                        fit: BoxFit.fill
                    )
                ),
                child: Stack(
                  children: <Widget>[
                    Positioned(
                      left: 30,
                      width: 80,
                      height: 200,
                      child: FadeAnimation(1, Container(
                        decoration: const BoxDecoration(
                            image: DecorationImage(
                                image: AssetImage('assets/images/light-1.png')
                            )
                        ),
                      )),
                    ),
                    Positioned(
                      left: 140,
                      width: 80,
                      height: 150,
                      child: FadeAnimation(1.3, Container(
                        decoration: const BoxDecoration(
                            image: DecorationImage(
                                image: AssetImage('assets/images/light-2.png')
                            )
                        ),
                      )),
                    ),
                    Positioned(
                      right: 40,
                      top: 40,
                      width: 80,
                      height: 150,
                      child: FadeAnimation(1.5, Container(
                        decoration: const BoxDecoration(
                            image: DecorationImage(
                                image: AssetImage('assets/images/clock.png')
                            )
                        ),
                      )),
                    ),
                    Positioned(
                      child: FadeAnimation(1.6, Container(
                        margin: const EdgeInsets.only(top: 50),
                        child: const Center(
                          child: Text("Welcome to INFO",
                            style: TextStyle(color: Colors.white, fontSize: 40, fontWeight: FontWeight.bold),),
                        ),
                      )),
                    )
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(30.0),
                child: Column(
                  children: <Widget>[
                    FadeAnimation(1.8, Container(
                      padding: const EdgeInsets.all(5),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(10),
                          boxShadow: const [
                            BoxShadow(
                                color: Color.fromRGBO(143, 148, 251, .2),
                                blurRadius: 20.0,
                                offset: Offset(0, 10)
                            )
                          ]
                      ),
                      child: Column(
                        children: <Widget>[
                          Container(
                            padding: const EdgeInsets.all(8.0),
                            decoration: BoxDecoration(
                                border: Border(bottom: BorderSide(color: Colors.grey[100]!))
                            ),
                            child: TextField(
                              controller: _usernameController,
                              decoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintText: "工号/域账号",
                                  hintStyle: TextStyle(color: Colors.grey[400])
                              ),
                            ),
                          ),
                          Container(
                            padding: const EdgeInsets.all(8.0),
                            child: TextField(
                              controller: _passwordController,
                              obscureText: !_showPwd,
                              decoration: InputDecoration(
                                border: InputBorder.none,
                                hintText: "密码",
                                hintStyle: TextStyle(color: Colors.grey[400]),
                                //右边图标设置
                                suffixIcon: GestureDetector(
                                  onTap: () {
                                    setState(() {
                                      _showPwd = !_showPwd;
                                    });
                                  },
                                  child: Padding(
                                    padding: const EdgeInsets.all(2),
                                    child: Image.asset(
                                      !_showPwd ?
                                      '${UIData.imageDir}/eye_close.png' :
                                      '${UIData.imageDir}/eye_open.png',),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    )),
                    const SizedBox(height: 30,),
                    FadeAnimation(2, GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () async {

                      },
                      child: Row(
                        children: [
                          Checkbox(
                              checkColor: Colors.white,
                              fillColor: MaterialStateProperty.all(UIData.primaryColor),
                              shape: const CircleBorder(),
                              value: _isRemember, onChanged: (val) {
                            setState(() {
                              _isRemember = val??false;
                            });
                          }),
                          const Text('记住密码'),
                        ],
                      ),
                    )),
                    FadeAnimation(2, GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () async {
                        EasyLoading.show();
                        var res = await AppRepository.login(
                            username: _usernameController.text.trim(),
                            password: _passwordController.text.trim());
                        EasyLoading.dismiss();
                        if (!res.valid()) {
                          res.showErr();
                          return;
                        }

                        SysInfo.instance.tokenType = 'Bearer ';
                        SysInfo.instance.accessToken = res.data['token'];
                        SysInfo.instance.isRemember = _isRemember;
                        SysInfo.instance.userName = _usernameController.text.trim();
                        SysInfo.instance.password = _passwordController.text.trim();
                        await SysInfo.instance.save();

                        int userNo = res.data['id'];
                        String fDate = formatDate(DateTime.now(), [yyyy, '-', mm, '-', dd]);
                        Navigator.pushReplacement(
                            context, MaterialPageRoute(builder: (context) => TabControl(userNo, fDate)));
                      },
                      child: Container(
                        height: 50,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            gradient: const LinearGradient(
                                colors: [
                                  Color.fromRGBO(143, 148, 251, 1),
                                  Color.fromRGBO(143, 148, 251, .6),
                                ]
                            )
                        ),
                        child: const Center(
                          child: Text("登录", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),),
                        ),
                      ),
                    )),
                    const SizedBox(height: 50,),
                    FadeAnimation(1.5, const Text("忘记密码？", style: TextStyle(color: Color.fromRGBO(143, 148, 251, 1)),)),
                  ],
                ),
              )
            ],
          ),
        )
    );
  }
}